﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PRO_DOCS.BLL.WIN.Authentication
{
    public static class LoggedInEmployeeSession
    {
        public static DAL.Database.PRO_DOCSDatabaseDataContext PRO_DOCSDatabaseDataContext
        {
            get { return new DAL.Database.PRO_DOCSDatabaseDataContext(DAL.Properties.Settings.Default.PRO_DOCSConnectionString); }
        }

        public static DAL.Database.SYSTEM_LOGIN_HISTORY CURRENT_LOGGED_IN_USER_SESSION
        { get; set; }


        public static void OPEN_LOGGED_IN_USER_SESSION()
        {
            Guid _LOGGED_IN_USER_SESSION_ID = Guid.NewGuid();

            PRO_DOCSDatabaseDataContext.proc_SYSTEM_LOGIN_HISTORYAddHistory
                (
                    _LOGGED_IN_USER_SESSION_ID,
                    LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                    DateTime.Now,
                    System.Environment.MachineName,
                    System.Environment.OSVersion.VersionString,
                    string.Empty,
                    string.Empty,
                    System.Environment.UserName,
                    LOGGED_IN_EMPLOYEE_DETAILS.LOGGED_IN_USER_SETTINGS.REQUIRED_LOGIN_LANGUAGE_ID
                );

            CURRENT_LOGGED_IN_USER_SESSION = (from history in PRO_DOCSDatabaseDataContext.SYSTEM_LOGIN_HISTORies
                                              where history.SYSTEM_LOGIN_HISTORY_ID.Equals(_LOGGED_IN_USER_SESSION_ID)
                                              select history).FirstOrDefault();
        }

        public static void CLOSE_LOGGED_IN_USER_SESSION()
        {
            PRO_DOCSDatabaseDataContext.proc_SYSTEM_LOGIN_HISTORYClose(
                    CURRENT_LOGGED_IN_USER_SESSION.SYSTEM_LOGIN_HISTORY_ID,
                    DateTime.Now);
        }

        public static void UPDATE_CHECK_IN_LOGGED_IN_USER_SESSION()
        {
            if (CURRENT_LOGGED_IN_USER_SESSION != null)
            {
                PRO_DOCSDatabaseDataContext.proc_SYSTEM_LOGIN_HISTORYUpdateLastCheckIn
                    (
                        CURRENT_LOGGED_IN_USER_SESSION.SYSTEM_LOGIN_HISTORY_ID,
                        DateTime.Now
                    );
            }
        }

        public static void CHECK_LOGGED_IN_USER_SESSION_STATUS()
        {

            CURRENT_LOGGED_IN_USER_SESSION = (from history in PRO_DOCSDatabaseDataContext.SYSTEM_LOGIN_HISTORies
                                              where history.SYSTEM_LOGIN_HISTORY_ID.Equals(CURRENT_LOGGED_IN_USER_SESSION.SYSTEM_LOGIN_HISTORY_ID)
                                              select history).FirstOrDefault();

            if (CURRENT_LOGGED_IN_USER_SESSION.LOGOUT_DATE_TIME.HasValue)
            {
                Application.Restart();
            }
        }
    }
}
